import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/config/const.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../api/interface/user_api.dart';
import '../../api/request/response_data.dart';
import '../../moudle/common_info.dart';
import '../../moudle/event_bus.dart';
import '../../moudle/message.dart';
import '../../moudle/permiss_handler/permission_operate.dart';
import '../../widget/cache_image.dart';
import '../../widget/common_widget.dart';
import '../../widget/top_device_select.dart';
import '../home/home.dart';
import 'min_select_device.dart';

class MinNewPage extends StatefulWidget {
  const MinNewPage({super.key});

  @override
  State<MinNewPage> createState() => _MinNewPageState();
}

class _MinNewPageState extends State<MinNewPage> with AutomaticKeepAliveClientMixin {

  List items = [
    {
      'img':'assets/home/min_product.png',
      'name':'Product'.tr,
      'value':''
    },
    {
      'img':'assets/home/min_add.png',
      'name':'Add Product'.tr,
      'value':''
    },
    {
      'img':'assets/home/min_wifi.png',
      'name':'Device Network Setting'.tr,
      'value':''
    },
    {
      'img':'assets/common/device_control_set.png',
      'name':'Settings'.tr,
      'value':''
    },
    {
      'img':'assets/home/min_contact.png',
      'name':'Contact Us'.tr,
      'value':''
    },
    {
      'img':'assets/home/min_version.png',
      'name':'Version'.tr,
      'value':baseVersion
    },
    {
      'name':"SPT Personnel".tr,
      'img':'assets/home/min_installer_icon.png',
      'value':''
    }
  ];

  Map feedbackInfo= {
    'spt.receive.email':{
      'value':''
    },
    'spt.phone':{
      'value':''
    },
  };
  bool isMail = true;
   late StreamSubscription _subscription;
   int status = -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getInfo();
    _getFeedbackInfo();
    _subscription = eventBus.on<UserInfoChange>().listen((val){
      if(mounted){setState(() {});}
    });
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _subscription.cancel();
  }

  _getInfo()async{
    getBaseUserInfo((){
      if(mounted){setState(() {});}
    });
    ResponseData res = await UserAPI.getInstallInfo();
    print('${res.data}');
    if(res.code == 200 && res.data != null){
      status = int.parse('${res.data['status'] ?? -1}');
    }
    if(mounted){
      setState(() {});
    }
  }

  _getFeedbackInfo()async{
    ResponseData res = await UserAPI.getFeedbackInfo();
    if(res.code == 200 && res.data != null){
      feedbackInfo = res.data;
      isMail = await canLaunchUrl(Uri.parse('mailto:${feedbackInfo['spt.receive.email']['value']??''}'));
      if(mounted){
        setState(() {});
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 30.w),
        child: SingleChildScrollView(
          child: Column(
            children: [
              SizedBox(height: ScreenUtil().statusBarHeight,),
              _topWidget(),
              SizedBox(height: 40.w,),
              Container(
                padding: EdgeInsets.all(40.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(16.w),
                  color: Color(0xff1e1d20)
                ),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: (){
                        
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8.w),
                        child: CacheImage(
                          image: baseUserInfo['avatar']??'assets/home/home_person.png',
                          placeholder: 'assets/home/home_person.png',
                          width: 128.w,
                          height: 128.w,
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                    SizedBox(width: 24.w,),
                    Expanded(child: Container(
                      height: 128.w,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.end,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            child: Text(baseUserInfo['nickname'] != null ? baseUserInfo['nickname']:baseUserInfo['firstName']!=null? baseUserInfo['firstName']:'user',style: TextStyle(
                              color: Colors.white,
                              fontSize: 36.sp,
                              fontWeight: FontWeight.w600
                            ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                          ),
                          SizedBox(height: 12.w,),
                          Container(
                            child: Text(baseUserInfo['email']??'',style: TextStyle(
                                color: Color.fromRGBO(255, 255, 255, 0.5),
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w400
                            ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                          )
                        ],
                      ),
                    )),
                    SizedBox(width: 16.w,),
                    GestureDetector(
                      onTap: (){
                        Navigator.of(context).pushNamed('MinInfoPage').then((_){
                          _getInfo();
                        });
                      },
                      child: Container(
                        width: 136.w,
                        height: 52.w,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: Color.fromRGBO(255, 255, 255, 0.1),
                          borderRadius: BorderRadius.circular(8.w)
                        ),
                        child: Text('Edit Profile'.tr,style: TextStyle(
                          color: Colors.white,
                          fontSize: 20.sp,
                          fontWeight: FontWeight.w400
                        ),),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 40.w,),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 40.w),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(16.w),
                    color: Color(0xff1e1d20)
                ),
                child: ListView.builder(itemBuilder: (ctx,index){
                  if(index == 1){
                    return Container();
                  }
                  Map item = items[index];
                  return GestureDetector(
                    onTap: (){
                      if(index == 0){

                        Navigator.of(context).pushNamed('MinPeoductsPage');

                        // showModalBottomSheet(context: context, builder: (ctx){
                        //   return MinSelectDeviceDialog(callBack: (){
                        //     eventBus.fire(DeviceInfoChange());
                        //   },);
                        // },isScrollControlled: true);
                      }else if(index == 1){
                        _showAddDeviceAlert();
                      }else if(index == 2){
                        Navigator.of(context).pushNamed('DeviceNetPage').then((val){
                          getDevicesList((){
                            setState(() {});
                          });
                        });
                      }else if(index == 3){
                        Navigator.of(context).pushNamed('MinSettingPage');
                      }else if(index == 4){
                        _showContactAlert();
                      }else if(index == 5){
                        Navigator.of(context).pushNamed('MinAboutPage');
                      }else if(index == 6){
                        Navigator.of(context).pushNamed('MinInstallerInfo',arguments: status).then((_){
                          _getInfo();
                        });
                      }
                    },
                    child: Container(
                      height: 120.w,
                      child: Column(
                        children: [
                          Expanded(child: Container(
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Image.asset(item['img'],width: 40.w,),
                                SizedBox(width: 8.w,),
                                Expanded(child: Text(item['name'],style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.w600,
                                    fontSize: 28.sp
                                ),)),
                                SizedBox(width: 24.w,),
                                // Container(
                                //   child: Text(item['value'],style: TextStyle(
                                //     color: Color.fromRGBO(255, 255, 255, 0.5),
                                //     fontSize: 24.sp,
                                //     fontWeight: FontWeight.w400
                                //   ),),
                                // ),
                                SizedBox(width: 0.w,),
                                Image.asset('assets/common/control_right.png',width: 48.w,),
                              ],
                            ),
                          )),
                          Visibility(child: Container(
                            height: 1.w,
                            color: Color.fromRGBO(255, 255, 255, 0.1),
                          ),visible: index != items.length-1,),
                        ],
                      ),
                    ),
                  );
                },padding: EdgeInsets.zero,shrinkWrap: true,physics: NeverScrollableScrollPhysics(),itemCount: items.length,),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _topWidget(){
    return Container(
      height: 44,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: (){
              _showDeviceChoose();
              // eventBus.fire(IndexSliderChange(true));
              // setState(() {
              //   isopen = true;
              // });
              // if(drawerKey.currentState != null && drawerKey.currentState!.isDrawerOpen){
              //   drawerKey.currentState?.closeSlider();
              //   eventBus.fire(IndexSliderChange(false));
              //   setState(() {
              //     isopen = false;
              //   });
              // }else{
              // eventBus.fire(IndexSliderChange(true));
              // drawerKey.currentState?.openSlider();
              // setState(() {
              //   isopen = true;
              // });
              // }
            },
            child: Row(
              children: [
                // Container(
                //   child: Image.asset('assets/home/home_person.png',width: 64.w,),
                // ),
                // SizedBox(width: 20.w,),
                Visibility(visible: true,child: Container(
                  constraints: BoxConstraints(
                      maxWidth: 260.w
                  ),
                  child: Text(baseUserInfo['firstName']!=null? baseUserInfo['firstName']:baseUserInfo['nickname']??'user',style: TextStyle(
                      color: whiteFontColor,
                      fontSize: 40.sp,
                      fontWeight: FontWeight.w600
                  ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                ),),
                SizedBox(width: 6.w,),
                Image.asset('assets/common/control_down.png',width: 48.w,)
              ],
            ),
          ),
          Visibility(child: Container(
            child: Text(cndcValue.isNotEmpty && double.parse('${cndcValue ?? '0'}') <0?'Discharging'.tr: cndcValue.isNotEmpty && double.parse('${cndcValue ?? '0'}') >0?'Charging'.tr:'Ready'.tr,style: TextStyle(
                color:cndcValue.isNotEmpty && double.parse('${cndcValue ?? '0'}') <0? themeColor : Color(0xff06df85),
                fontSize: 28.sp,
                fontWeight: FontWeight.w600
            ),maxLines: 1,overflow: TextOverflow.ellipsis,),
          ),visible: baseDevice != null && baseDevice?['status'].toString() != '2',),
          // Container(
          //   child: Image.asset('assets/home/home_logo.png',height: 40.w,),
          // )
          // GestureDetector(
          //   onTap: (){
          //     JhPickerTool.showStringPicker(context,
          //         data: _list,
          //         clickCallBack: _selectType,
          //         normalIndex: 0);
          //   },
          //   child: Row(
          //     children: [
          //       SizedBox(width: 20.w,),
          //       Text(home_page_change_device_text.tr,style: TextStyle(
          //           color: fontColor
          //       ),)
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  _showDeviceChoose(){
    return SmartDialog.show(builder: (ctx){
      return TopDeviceSelect(
        callBack: (type){
          if(type == 1){
            _showAddDeviceAlert();
          }
        },
      );
    },alignment: Alignment.topCenter,animationTime: Duration(milliseconds: 200));
  }

  _showAddDeviceAlert(){
    SmartDialog.show(builder: (ctx){
      return Container(
        height: 530.w,
        padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: 48.w),
        decoration: BoxDecoration(
            color: Color(0xff1E1E1E),
            borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
        ),
        child: Column(
          children: [
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Add new device',style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                  )
                ],
              ),
            ),
            SizedBox(height: 100.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                getCameraPermission(context, (){
                  Navigator.of(context).pushNamed('ScanPage').then((val){
                    if(mounted){setState(() {});}
                  });
                });
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: themeColor,
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Scan Your Device',style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: 32.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                Navigator.of(context).pushNamed('MinAddDeviceInput').then((val){
                  print('base===' + baseDevice.toString());
                  setState(() {});
                });
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xff2A2A2A),
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Manual Entry'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
          ],
        ),
      );
    },alignment: Alignment.bottomCenter);
  }

  _showContactAlert(){
    SmartDialog.show(builder: (ctx){
      return Container(
        padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: 48.w),
        decoration: BoxDecoration(
            color: Color(0xff1E1E1E),
            borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Contact Us'.tr,style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                  )
                ],
              ),
            ),
            SizedBox(height: 32.w,),
            Container(
              height: 1.w,
              color: Color.fromRGBO(255, 255, 255, 0.1),
            ),
            SizedBox(height: 32.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                SmartDialog.show(builder: (ctx){
                  return connectItem(feedbackInfo['spt.phone']['value']??'', 'assets/home/min_phone.png', 1);
                },alignment: Alignment.center);
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: themeColor,
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Call: ${feedbackInfo['spt.phone']['value']??''}',style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: 32.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                SmartDialog.show(builder: (ctx){
                  return connectItem(feedbackInfo['spt.receive.email']['value']??'', 'assets/home/min_emial.png', 2);
                },alignment: Alignment.center);
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xff2A2A2A),
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Email: ${feedbackInfo['spt.receive.email']['value']??''}',style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: ScreenUtil().bottomBarHeight+12.w,)
          ],
        ),
      );
    },alignment: Alignment.bottomCenter);
  }

  connectItem(String text,String img,int type){
    return Container(
      width: 640.w,
      padding: EdgeInsets.all(32.w),
      decoration: BoxDecoration(
          color: Color(0xff3C3C3C),
          borderRadius: BorderRadius.circular(24.w)
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            child: Row(
              children: [
                Container(
                  width: 40.w,
                ),
                Expanded(child: Text(type==1?'Call number'.tr:'Send an email'.tr,style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp,
                ),textAlign: TextAlign.center,)),
                Container(
                  width: 40.w,
                  child:  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 32.sp,color: Color(0xff999999),),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 90.w,),
          Container(
            height: 84.w,
            alignment: Alignment.center,
            // padding: EdgeInsets.symmetric(horizontal: 20.w),
            // decoration: BoxDecoration(
            //     color: Color(0xff494949),
            //     borderRadius: BorderRadius.circular(8.w)
            // ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Image.asset(img,width: 36.w,),
                // SizedBox(width: 24.w,),
                Text(text,style: TextStyle(
                    color: Colors.white,
                    fontSize: 50.sp
                ),)
              ],
            ),
          ),
          SizedBox(height: 108.w,),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // GestureDetector(
                //   onTap: (){
                //     SmartDialog.dismiss();
                //   },
                //   child: Container(
                //     child: Text('Cancel',style: TextStyle(
                //         color: Color(0xff666666),
                //         fontSize: 28.sp,
                //         fontWeight: FontWeight.w600
                //     ),),
                //     decoration: BoxDecoration(
                //         color: Color(0xffE8E8E8),
                //         borderRadius: BorderRadius.circular(84.w)
                //     ),
                //     width: 260.w,
                //     height: 92.w,
                //     alignment: Alignment.center,
                //   ),
                // ),
                // SizedBox(width: 32.w,),
                GestureDetector(
                  onTap: ()async{
                    SmartDialog.dismiss();
                    if(type == 1){
                      if(await canLaunchUrl(Uri.parse('tel:${feedbackInfo['spt.value.phone']['value']}'))){
                        launchUrl(Uri.parse('tel:${feedbackInfo['spt.value.phone']['value']}'));
                      }else{
                        await Clipboard.setData(ClipboardData(text: '${feedbackInfo['spt.value.phone']['value']}'));
                        showToast(connect_us_page_item_copy_success.tr);
                      }
                    }else{
                      if(await canLaunchUrl(Uri.parse('mailto:$text'))){
                        launchUrl(Uri.parse('mailto:$text'));
                      }else{
                        await Clipboard.setData(ClipboardData(text: text));
                        showToast(connect_us_page_item_copy_success.tr);
                      }
                    }
                  },
                  child: Container(
                    decoration: BoxDecoration(
                        color: Color(0xff3C55F8),
                        borderRadius: BorderRadius.circular(84.w)
                    ),
                    width: 260.w,
                    height: 92.w,
                    alignment: Alignment.center,
                    child: Text(type==1?'Call'.tr:'Send'.tr,style: TextStyle(
                        color: Colors.white,
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => false;


}
